# Define your item pipelines here
#
# Don't forget to add your pipeline to the ITEM_PIPELINES setting
# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html


# useful for handling different item types with a single interface
from itemadapter import ItemAdapter


class SpidersPipeline:
    def process_item(self, item, spider):
        return item

#连接mysql
import pymysql
class MYSQLPipeline():
    def open_spider(self,spider):
        self.db_conn=pymysql.connect("localhost","root","123456","scr_db",3306,charset='utf8')
        self.db_cur=self.db_conn.cursor()

    def close_spider(self,spider):
        self.db_conn.commit()
        self.db_conn.close()

    def process_item(self,item,spider):
        self.insert_db(item)
        return item

    def insert_db(self,item):
        values = (item['name'],item['price'])
        sql = 'insert into books values (%s,%s)'
        self.db_cur.execute(sql,values)